<template>
	<view class="content">
		<u-form :model="form" ref="uForm" :error-type="errorType">
			<view class="formBox">
				<view class="title">优惠券类型</view>
				<view class="f-c-sb tag">
					<view 
						class="tabTag"
						:class="item.id == form.type?'active':''" 
						v-for="(item, index) in type" 
						:key="index"
						@click="selectType(item.id)"
					>{{item.name}}</view>
				</view>
				<view class="f-c-fs">
					<u-radio-group v-model="useAreaTxt">
						<u-radio
							@tap="useAreaRadioChange(item.id)" 
							v-for="(item, index) in useArea" :key="index" 
							:name="item.name"
							:checked="item.checked"
							:value="item.id"
						>
							{{item.name}}
						</u-radio>
					</u-radio-group>
				</view>
			</view>
		
			<view class="formBox">
				<view class="title">基础信息</view>
				<u-form-item label="优惠券名称" label-width="150"  prop="name"  required>
					<u-input v-model="form.name" placeholder="请输入名称" input-align="right" />
				</u-form-item>
				<u-form-item label="优惠券金额" label-width="150" prop="money"  required>
					<u-input type="digit" v-model="form.money" placeholder="请输入金额/元"  input-align="right" />
				</u-form-item>
				<u-form-item label="发送节点" label-width="150" prop="sendType" required>
					<u-radio-group v-model="sendTypeTxt" class="f-c-fe">
						<u-radio
                @change="sendTypeCheckboxChange(item.id)"
                :checked="item.checked"
                v-for="(item, index) in sendType" :key="index"
                :name="item.name"
            >{{ item.name }}
            </u-radio>
          </u-radio-group>
        </u-form-item>
        <u-form-item label="使用条件" label-width="150" prop="conditionMoney" required>
          <u-input type="digit" v-model="form.conditionMoney" placeholder="请输入满多少/元可以使用" input-align="right"/>
        </u-form-item>
        <u-form-item label="优惠券总数" label-width="150" prop="sendTotal" required>
          <u-input type="number" v-model="form.sendTotal" placeholder="请输入/张" input-align="right"/>
        </u-form-item>
        <u-form-item label="使用门店" label-width="150" prop="useStoreType" required>
          <u-radio-group v-model="useStoreTypeTxt" class="f-c-fe">
            <u-radio
                @tap="storeRadioChange(item.id)"
                v-for="(item, index) in store" :key="index"
                :name="item.name"
                :checked="item.checked"
                :value="item.id"
            >
              {{ item.name }}
            </u-radio>
					</u-radio-group>
				</u-form-item>
				<u-form-item label="使用说明" label-position="top">
						<u-input v-model="form.useNotice" :type="useNoticeTxt.type" :height="useNoticeTxt.height" :auto-height="useNoticeTxt.autoHeight" placeholder="请输入说明" />
				</u-form-item>
				</view>
				
				<view class="formBox">
          <view class="title">时间信息</view>
          <view class="labelText"><span style='    color: #fa3534;'>*</span> 发放时间</view>
          <view class="f-c-fs">
            <u-form-item class="f-c-fs" prop="sendTimeStart">
              <u-input type="text" v-model="form.sendTimeStart" disabled @click="selStart" placeholder="请选择开始时间"/>
              <u-picker
                  mode="time"

                  v-model="startShow"
                  :params="params"
                  end-year="2100"
                  @confirm="confirmStart"
								title="请选择发放开始时间"
								
							></u-picker>
						</u-form-item>一
						<u-form-item  prop="sendTimeEnd">
							<u-input type="text" v-model="form.sendTimeEnd" disabled  @click="selEnd" placeholder="请选择结束时间"/>
							<u-picker
								mode="time"
								
								v-model="endShow"
								:params="params"
								end-year="2100"
								@confirm="confirmEnd"
								title="请选择发放结束时间"
								 
							></u-picker>
						</u-form-item>
					</view>
					<u-form-item label="使用有效期" label-width="100%" label-position="top" required>
						<u-radio-group  v-model="useTimeTypeName" class="f-c-fe">
							<u-radio :checked="true" name="useTimeType1" @change="useTime(1)" :key="1">
								<view class="f-c-fs">
									<u-form-item prop="useTimeStart">
										<u-input type="text" v-model="form.useTimeStart" disabled @click="useStart" placeholder="请选择开始时间" />
										<u-picker
											mode="time"
											
											v-model="useStartShow"
											:params="params"
											end-year="2100"
											@confirm="confirmUserStart"
											title="请选择开始使用时间"
										></u-picker>
									</u-form-item>一
									<u-form-item prop="useTimeEnd">
										<u-input type="text" v-model="form.useTimeEnd" disabled @click="useEnd" placeholder="请选择结束时间"/>
										<u-picker
											mode="time"
											
											v-model="useEndShow"
											:params="params"
											end-year="2100"
											@confirm="confirmUserEnd"
											title="请选择结束使用时间"
										></u-picker>
									</u-form-item>
								</view>
							</u-radio>
							<u-radio :checked="false" name="useTimeType2" @change="useTime(2)" :key="2">
								<u-form-item label="领券后有效天数" label-width="250" prop="useTime">
									<u-input type="number" v-model="form.useTime" placeholder="0代表长期有效" input-align="right" />
								</u-form-item>
							</u-radio>
						</u-radio-group>
					</u-form-item>
					
					
				</view>
				<view class="submitBtn" @click="submit">完成创建</view>
				<!--消息框开始 -->
				<view>
					<u-toast ref="uToast" />
				</view>
				<!--消息框结束 -->
		</u-form>
		
		
		
	</view>
</template>

<script>
import {couponSave} from '@/api/marketing.js';
import {mapGetters} from 'vuex';

export default {
  data() {
    return {
      useTimeTypeName: 'useTimeType1',
      startShow: false,
      endShow: false,
      useStartShow: false,
      useEndShow: false,
      defaultSelector: [0],
      params: {
        year: true,
					month: true,
					day: true,
					hour: false,
					minute: false,
					second: false	
				},
				message:'',
				errorType: ['toast','message'],
				startShow: false,
				endShow:false,
				mode: 'date',
				selectList:[],
				type:[
					{
						id:1,
						name:'钣喷满减'
					},
					{
						id:2,
						name:'洗车满减'
					},
					{
						id:3,
						name:'保养满减'
					},
					{
						id:4,
						name:'商城满减'
					},
					{
						id:5,
						name:'美容满减'
					},
					{
						id:6,
						name:'购车满减'
					},
				],
				useAreaTxt:'全场通用',
				useArea:[
					{
						id:1,
						name: '全场通用',
						checked: true
					},
					{
						id:2,
						name: '指定服务项目',
						checked: false
					},
				],
				sendTypeTxt:'推送',
				sendType:[
					{
						id:1,
						name:"推送",
						checked: false
					},
					{
						id:4,
						name:"洗车",
						checked: false
					}
				],
				useStoreTypeTxt:'当前门店',
				store:[
					{
						id:1,
						name:'当前门店',
						value:1,
						checked:true
					},
					{
						id:2,
						name:'其他门店',
						value:2,
						checked:false
					}
				],
				useNoticeTxt:{
					show: true,
					mode: 'range',
					type: 'textarea',
					height: 100,
					autoHeight: true
				},
				form: {
					type:1,
					useArea:1,
					serviceItems:'',
					name: '',
					money:'',
					sendType:1,
					conditionMoney:'',
					sendTotalType:2,
					sendTotal:'',
					useStoreType:1,
					useStores:'',
					useNotice:'',
					sendTimeStart:'',
					sendTimeEnd:'',
					useTimeType:1,
					useTimeStart:'',
					useTimeEnd:'',
					useTime:'',
					storeBasicId:''
				},
				rules: {
					name: [
						{ 
							required: true, 
							message: '请输入优惠券名称', 
							trigger: ['change','blur']
						}
					],
					money: [
						{
							required: true,
							message: '请输入优惠券金额', 
							trigger: ['change','blur']
						},
						{
							pattern: /^(([1-9]\d*)(\.\d{1,2})?)$|(0\.0?([1-9]\d?))$/g,
							// 正则检验值转为金额格式
							transform(value) {
								return Number(value);
							},
							message: '优惠券金额格式应为10.00'
						}
					],
					conditionMoney:[
						{
							required: true,
							message: '请填写使用条件', 
							trigger: ['change','blur']
						},
						{
							// 自定义验证函数，见上说明
							validator: (rule, value, callback) => {
								return this.$u.test.amount(value);
							},
							message: '金额格式不正确',
							// 触发器可以同时用blur和change
							trigger: ['change', 'blur']
						}
					],
					sendTotal:[
						{
							required: true,
							message: '请填写优惠券总数', 
							trigger: ['change','blur']
						},
						{

							pattern: /^\d+$/g,
							// 正则检验值只能为数字
							transform(value) {
								if(value==0){
									return false
								}else{
									return Number(value);
								}
							},
							message: '请填写大于0的整数',
							trigger: ['change','blur']
						}
					],
					sendTimeStart:[
						{
							required: true,
							message: '请选择发放开始时间', 
							trigger: ['change','blur']
						},
						{
							validator: this.validationStarttime,
							message: '发放开始时间不能晚于结束时间',
							trigger: ['change','blur']
						}
					],
					sendTimeEnd:[
						{
							required: true,
							message: '请选择发放结束时间', 
							trigger: ['change','blur']
						},
					    {
							validator: this.validationEndtime,
							message: '发放结束时间不能早于开始时间',
							trigger: ['change','blur']
					    }
					]
					
				}				
			};
		},
    computed: {
      ...mapGetters(['userInfo', 'selectStore', 'selectWorkItem'])
    },
		onReady() {
			this.$refs.uForm.setRules(this.rules);
			this.form.useStores=this.userInfo.storeBasicId;
			this.form.storeBasicId=this.userInfo.storeBasicId;
			
		},
		onload(){
			this.$store.commit('setSelectStore', []);
		},
		onUnload() {
      this.$store.commit('setSelectStore', []);
      this.$store.commit('setSelectWorkItem', []);
      this.$store.commit('setSelectCar', []);
      this.$store.commit('setSelectShopStr', []);
    },
		onShow() {
			let storeArray=[];
			let shopArray=[];
			console.log(this.selectStore);
			if(this.selectStore.length){
				this.selectStore.forEach((val,index)=>{
					storeArray.push(val.storeId);
				})
				this.form.useStores=storeArray.toString();
				
				this.store[1].name="已选中"+storeArray.length+"家门店";
				this.useStoreTypeTxt="已选中"+storeArray.length+"家门店";
			}
			let pages = getCurrentPages();
			let currPage = pages[pages.length - 1];
			this.selectList=currPage.data.selectList;
			if(this.selectList.length){
				
				if(this.form.type==1 || this.form.type==2 || this.form.type==3 || this.form.type==5){
					this.selectList.forEach((val,index)=>{
						shopArray.push(val.optionNo);
					})
					this.useArea[1].name="已选中"+shopArray.length+"项服务";
					this.useAreaTxt="已选中"+shopArray.length+"项服务";
					
				}else if(this.form.type==6){
					this.selectList.forEach((val,index)=>{
						shopArray.push(val.modelId);
					})
					this.useArea[1].name="已选中"+shopArray.length+"辆车型";
					this.useAreaTxt="已选中"+shopArray.length+"辆车型";
					
				}else{
					this.selectList.forEach((val,index)=>{
            shopArray.push(val.gsId);
          })
          this.useArea[1].name = "已选中" + shopArray.length + "个商品";
          this.useAreaTxt = "已选中" + shopArray.length + "个商品";

        }

        this.form.serviceItems = shopArray.toString();
        console.log(shopArray);

      } else {
        this.useAreaTxt = "全场通用";

      }
			this.useTime(1)
		},
		methods: {
			// 自定义验证规则(校验开始日期)
			validationStarttime: function (rule, value, callback) {
			  // 比较时间戳(进行运算的时候会自动转换成时间戳进行运算，不运算的时候，显示中国标准时间格式)
			  if (
				new Date(this.form.sendTimeEnd) - new Date(value) <= 0 &&
				this.form.sendTimeEnd &&
				value
			  ) {
				return callback(new Error('*发放开始日期不能晚于发放结束日期'))
			  }
			  callback()
			},
			// 自定义验证规则(校验截止日期)
			validationEndtime: function (rule, value, callback) {
			  // 比较时间戳(进行运算的时候会自动转换成时间戳进行运算，不运算的时候，显示中国标准时间格式)
			  if (
				new Date(value) - new Date(this.form.sendTimeStart) <= 0 &&
				this.form.sendTimeEnd &&
				value
			  ) {
				return callback(new Error('*发放结束日期不能早于发放开始日期'))
			  } callback()
			},
			// 自定义验证规则(校验开始日期)
			validationUseStarttime: function (rule, value, callback) {
			  // 比较时间戳(进行运算的时候会自动转换成时间戳进行运算，不运算的时候，显示中国标准时间格式)
			  if (
				new Date(this.form.useTimeEnd) - new Date(value) <= 0 &&
				this.form.useTimeEnd &&
				value
			  ) {
				return callback(new Error('*使用开始日期不能晚于使用结束日期'))
			  }
			  
			  callback()
			},
			// 自定义验证规则(校验截止日期)
			validationUseEndtime: function (rule, value, callback) {
			  // 比较时间戳(进行运算的时候会自动转换成时间戳进行运算，不运算的时候，显示中国标准时间格式)
			  if (
				new Date(value) - new Date(this.form.useTimeStart) <= 0 &&
				this.form.useTimeEnd &&
				value
			  ) {
				return callback(new Error('*使用结束日期不能早于使用开始日期'))
			  } 
			  
			  callback()
			},
			validationUseStarttime2: function (rule, value, callback) {
			  if(new Date(this.form.useTimeStart)-new Date(this.form.sendTimeStart)<0){
				  return callback(new Error('*使用开始日期不能早于发放开始日期'))
			  }
			  callback()
			},
			// 自定义验证规则(校验截止日期)
			validationUseEndtime2: function (rule, value, callback) { 
			  if(new Date(this.form.useTimeEnd)-new Date(this.form.sendTimeEnd)<0){
			  	 return callback(new Error('*使用结束日期不能早于发放结束日期'))
			  }
			  callback()
			},
			selectType(id) {
        this.form.type = id;
        this.useAreaTxt = '全场通用'
        this.useArea[1].name = "指定服务项目";
        this.$store.commit('setSelectWorkItem', []);
        this.$store.commit('setSelectCar', []);
        this.$store.commit('setSelectShopStr', []);
      },
			useAreaRadioChange(id){
				this.form.useArea=id;
				if(id==2){
					if(this.form.type==4){
						this.$navigateTo('/pages/selectShop/selectShop',{});
					}else if(this.form.type==1 || this.form.type==2 || this.form.type==3 || this.form.type==5){
						this.$navigateTo('/marketing/coupons/selectWorkItem',{type:this.form.type});
					}else{
						this.$navigateTo('/marketing/coupons/selectCar',{});
					}
					
				}
				console.log(this.form.useArea);
			},
			sendTypeCheckboxChange(id){
				this.form.sendType=id;
			},
			storeRadioChange(id){
				this.form.useStoreType=id;
				if(id==2){
					this.$navigateTo('/pages/selectStore/selectStore',{});
				}else{
					this.form.useStores=this.userInfo.storeBasicId;
				}
			},
			
			useTime(id){
				if(id==1){
					this.rules.useTimeStart=[{
						required: true,
						message: '请选择使用开始时间', 
						trigger: ['change','blur']
					},
					{
						validator: this.validationUseStarttime,
						message: '使用开始时间不能晚于结束时间',
						trigger: ['change','blur']
					},
					{
						validator: this.validationUseStarttime2,
						message: '使用开始日期不能早于发放开始日期',
						trigger: ['change','blur']
					}];
					this.rules.useTimeEnd=[{
						required: true,
						message: '请选择使用结束时间', 
						trigger: ['change','blur']
					},
					{
						validator: this.validationUseEndtime,
						message: '使用开始时间不能晚于结束时间',
						trigger: ['change','blur']
					},
					{
						validator: this.validationUseEndtime2,
						message: '使用结束日期不能早于发放结束日期',
						trigger: ['change','blur']
					}];
					delete this.rules.useTime
					
				}
				if(id==2){
					this.rules.useTime=[
						{
							required: true,
							message: '请填写领券后有效天数', 
							trigger: ['change','blur']
						}
					];
					delete this.rules.useTimeStart
					delete this.rules.useTimeEnd
				}
				this.form.useTimeType=id;
				this.checked=true;
				console.log(this.rules,this.form);
			},
			showToast() {
				this.$refs.uToast.show({
					title: this.massage,
					type: 'default'
				})
			},
			getDate(type) {
				let date = new Date();
				let year = date.getFullYear();
				let month = date.getMonth() + 1;
				let day = date.getDate();
				let hour=date.getHours();
				let minute=date.getMinutes();
				let second=date.getSeconds();
				return year + '-' + month + '-' + day;
				
			},
			selStart() {
				this.startShow = true;
			},
			selEnd() {
				this.endShow = true;
			},
			useStart() {
				this.useStartShow = true;
			},
			useEnd() {
				this.useEndShow = true;
			},
			confirmStart(e) {
				this.form.sendTimeStart = e.year + '-' + e.month + '-' + e.day;
				
			},
			confirmEnd(e) {
				this.form.sendTimeEnd = e.year + '-' + e.month + '-' + e.day;
			},
			confirmUserStart(e) {
				this.form.useTimeStart = e.year + '-' + e.month + '-' + e.day;
				
			},
			confirmUserEnd(e) {
				this.form.useTimeEnd = e.year + '-' + e.month + '-' + e.day;
			},
			submit() {
				this.$refs.uForm.validate(valid => {
					if (valid) {
						console.log(this.form);
						couponSave(this.form).then(res=>{
							console.log(res);
							if(res.code==1){
								this.$put('isCreatStatus','1')
								uni.switchTab({
									url: '/pages/marketing/marketing'
								});
							}else{
								this.$refs.uToast.show({
									title: res.msg,
									type: 'default'
								})
							}
						});
						
					} else {
						console.log('验证失败');
					}
					
				});
				
				
			}
		}
	}
</script>

<style lang="less">
.content {
	width: 100%;
	min-height: 100vh;
	background: #f5f5f5;
	padding: 20rpx 0;
	box-sizing: border-box;
	font-family: "微软雅黑";
	.formBox{
		.title{
			border-bottom: none;
		}
		.tag{
			padding:20rpx 0;
			border-bottom: 1px solid #efefef;
			flex-wrap: wrap;
			.tabTag{
				width: 180rpx;
				height: 70rpx;
				background-color: #d3d3d3;
				color:#fff;
				text-align: center;
				line-height: 70rpx;
				margin-bottom: 20rpx;
				border-radius: 5rpx;
			}
			.active{
				background-color: #177fff;
			}
		}
		
	}
}

.submitBtn{
	width: 710rpx;
	height: 100rpx;
	background: #177fff;
	border-radius: 13rpx;
	font-size: 32rpx;
	font-weight: bold;
	color: #ffffff;
	text-align: center;
	line-height: 100rpx;
	margin: 0 auto;
}
</style>
